import App from './App'

// #ifndef VUE3
import Vue from 'vue'
import './uni.promisify.adaptor'
Vue.config.productionTip = false
App.mpType = 'app'
const app = new Vue({
  ...App
})
app.$mount()
// #endif

// #ifdef VUE3
import { createSSRApp } from 'vue'
export function createApp() {
  const app = createSSRApp(App)
  return {
    app
  }
}
// #endif

import navTop from '@/components/navTop.vue';
Vue.component('navTop', navTop);

import * as zwyFilter from './util/zwyFilter.js'
Object.keys(zwyFilter).forEach(key => {
	Vue.filter(key, zwyFilter[key])
})


Vue.prototype.zwyLogin = function() {
	console.log('zwyLogin');
	return new Promise((resolve, reject) => {
		uni.login({
			success: (loginRes) => {
				let postData = {
					code: loginRes.code
				}
				if (loginRes.anonymousCode) {
					postData['anonymousCode'] = loginRes.anonymousCode;
				}

				if (uni.getStorageSync('openId')) {
					postData['openId'] = uni.getStorageSync('openId');
				}
				uniCloud.callFunction({
					name: 'login',
					data: postData
				}).then(isRes => {
					if (isRes && isRes.result && isRes.result.openid) {
						uni.setStorageSync('userInfo', isRes.result);
						uni.setStorageSync('openId', isRes.result.openid);
					}
					console.log('getApp().globalData.zwyQueue', getApp().globalData
						.zwyQueue);
					let zwyQueue = getApp().globalData.zwyQueue;
					if (zwyQueue.length > 0) {
						for (let i = 0; i < zwyQueue.length; i++) {
							this.zwyRequest(zwyQueue[i].postData);
						}
						getApp().globalData.zwyQueue = [];
					}
					resolve();
				}).catch(res => {
					resolve();
				})
			}
		});
	})
}

Vue.prototype.zwyRequest = function(postData) {
	console.log('postData', postData);
	let tempUrl = postData.url || postData.name;
	if (!tempUrl) return;
	let tempData = postData.data || {};
	let tempOpenId = wx.getStorageSync('openId') || '';
	return new Promise((resolve, reject) => {
		console.log('tempOpenId',tempOpenId);
		if (tempOpenId) {
			tempData['openId'] = tempOpenId;
			uniCloud.callFunction({
				name: tempUrl,
				data: tempData
			}).then(res => {
				if(res && res.result && res.result.msg){
					uni.showToast({
						title:res.result.msg,
						icon:'none'
					})
				}
				
				if (!postData.resolve) resolve(res);
				else postData.resolve(res);
			})
		} else {
			postData['resolve'] = resolve
			getApp().globalData.zwyQueue.push({
				postData
			});
		}
	})
}